/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution6 {
    public int postIndex;
    private TreeNode buildTreeChild(int[] postorder,int[] inorder,int inbegin,int inend) {
        //对于左树:left = left   right = mid - 1;
        //对于右树:left = mid + 1    right = right
        //当遍历到只剩下一个根节点时就结束
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode((char) postorder[postIndex]);
        //找到当前根节点 在中序遍历中的位置
        int rootIndex = findInorderIndex(inorder, postorder[postIndex],inbegin,inend);
        postIndex--;
        //前序遍历是：跟左右
        //而后序遍历是:左右根
        root.right = buildTreeChild(postorder,inorder,rootIndex+1,inend);

        root.left = buildTreeChild(postorder,inorder,inbegin,rootIndex-1);

        return root;

    }

    private int findInorderIndex(int[] inorder,int val,int inbegin,int inend) {
        for(int i = inbegin;i <= inend;i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }

    
       
    
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = inorder.length - 1;
        return buildTreeChild(postorder,inorder,0,inorder.length-1);
    } 
}